import WxValidate from '../../lib/WxValidate.js'

const app = getApp()


Page({


    onLoad: function (option) {
        // 初始化验证方法
        this.initValidate()
        console.log(option)
        console.log(wx.getStorageSync('user').openid)

        this.setData({
            deviceId: option.deviceId + "",
        });
        // this.setData({
        //   deviceId:'7C:9E:BD:04:95:E6'
        // })
        //this.openBluetoothAdapter()
        this.doConnect()
    },

    data: {
        chePaiHao: "默认名称",
        wiffZhangHao: "",
        wiffMiMa: "",
        cuoWuChePaiHao: false,


        openid: wx.getStorageSync('user').openid,


        sao_miao_loading: false,//开始扫描”按钮是否出现等待
        input_fa_song_value: "",//发送intpu里的值
        //蓝牙相关
        connected: false,//蓝牙是否连接
        canWrite: false,
        chs: [],
        deviceId: "",
        name: "",
        serviceId: "",
        characteristicId: ""
        //蓝牙相关结束
    },


    doConnect: function () {
        var that = this;

        console.log(that.data.deviceId)

        // if (that.data.client && that.data.client.isConnected()) {
        //   wx.showToast({
        //     title: '不要重复连接'
        //   })
        //   return
        // }
        // var client = new Client("wss://www.zcxbb.com/mqtt", that.randomString());
        let client = app.globalData.client
        try {


            // client.onMessageArrived = function (msg) {
                //console.log(msg)

                // if (that.data.deviceId.replace(/:/g, "") === msg.topic) {
                    //console.log("接到该设备心跳：" + that.data.deviceId.replace(/:/g, ""))


                    //let sql = "update qi_che_she_bei set ming_cheng='" + that.data.chePaiHao + "' ,  openid='" + wx.getStorageSync('user').openid + "' where device_id='" + that.data.deviceId + "'"
            let sql = "update qi_che_she_bei set ming_cheng='" + that.data.deviceId + "' ,  openid='" + wx.getStorageSync('user').openid + "' where device_id='" + that.data.deviceId + "'"
                    wx.request({
                        url: app.globalData.urlGlobal + '/commonZwl/getZwl', //url
                        method: 'GET', //请求方式
                        header: {
                            'Content-Type': 'application/json',
                        },
                        data: {
                            sql: sql,  //参数
                        },
                        success: function (res) {
                            //debugger
                            let data = res.data.rtn;
                            // if(data.length>=0){
                            wx.showToast({
                                title: '绑定成功'
                            })
                            setTimeout(()=>{
                                wx.navigateTo({
                                    url: '/pages/index/index',
                                })
                            },1000)

                            // wx.showModal({
                            //   title:"绑定成功",
                            //   showCancel:false,
                            //   success(res) {
                            //     if(res.confirm){
                            //       wx.navigateTo({
                            //         url: '/pages/index/index',
                            //       })
                            //     }
                            //   }
                            // })
                            // }

                        },
                        fail: function () {
                            console.log("请求数据失败");
                        },
                        complete: function () {
                            // complete
                        }
                    })


                // }
                if (typeof that.data.onMessageArrived === 'function') {
                    return that.data.onMessageArrived(msg)
                }

                // wx.showModal({
                //   title: msg.destinationName,
                //   content: msg.payloadString
                // })
            // }

            client.onConnectionLost = function (responseObject) {
                if (typeof that.data.onConnectionLost === 'function') {
                    return that.data.onConnectionLost(responseObject)
                }
                if (responseObject.errorCode !== 0) {
                    console.log("onConnectionLost:" + responseObject.errorMessage);
                    if (responseObject.errorCode === 8) {
                        that.doConnect()
                    }
                }
            }


            let subTopic = that.data.deviceId.replace(/:/g, "")
            that.doSubscribe(subTopic)


        } catch (e) {
            console.log(e)
        }

    },
    doSubscribe: function (subTopic) {

        this.subscribe(subTopic, {
            qos: 1
        })
    },
    subscribe: function (filter, subscribeOptions) {
        let that = this
        // 订阅
        var client = app.globalData.client
        if (client && client.isConnected()) {
            wx.showToast({
                title: '服务器连接成功'
            })
            return client.subscribe(filter, subscribeOptions);
        } else {
            app.globalData.mqttConnetc(app.globalData);
            //that.doConnect()
        }
        // wx.showToast({
        //   title: '订阅失败',
        //   icon: 'success',
        //   duration: 2000
        // })
    },


    mqttSend: () => {
        wx.navigateTo({
            url: '/pages/index/index',
        })
    },

    //提交处理函数
    formSubmit: function (e) {


        let issueInfo = e.detail.value

        //校验表单
        if (!this.WxValidate.checkForm(issueInfo)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }

        // wx.showLoading({
        //   title: '加载中',
        //   mask: true
        // })

        //let val='BW'+issueInfo.wiffZhangHao+","+issueInfo.wiffMiMa
        let val = issueInfo.wiffZhangHao + "," + issueInfo.wiffMiMa

        this.setData({
            chePaiHao: issueInfo.chePaiHao
        })


        function writeCallBack(res) {
            console.log(JSON.stringify(res))
        }

        this.writeBLECharacteristicValue(val)

    },

    //报错
    showModal(error) {
        wx.showModal({
            content: error.msg,
            showCancel: false,
        })
    },

    //验证函数
    initValidate() {
        const rules = {
            chePaiHao: {
                required: true,
                maxlength: 128
            },
            wiffZhangHao: {
                required: true,
                maxlength: 128
            },
            wiffMiMa: {
                required: true,
                maxlength: 128
            },

        }
        const messages = {
            chePaiHao: {
                required: '请输入车牌号',
                minlength: '最多只能输入128个字符'
            },
            wiffZhangHao: {
                required: '请输入wiff账号',
                minlength: '最多只能输入128个字符'
            },
            wiffMiMa: {
                required: '请输入wiff密码',
                minlength: '最多只能输入128个字符'
            },

        }
        this.WxValidate = new WxValidate(rules, messages)
    },


    openBluetoothAdapter() {
        let that = this;
        wx.openBluetoothAdapter({
            success: (res) => {
                console.log('openBluetoothAdapter success', res)
                //this.startBluetoothDevicesDiscovery()
                this.createBLEConnection();
                that.setData({
                    connected: true
                })
            },
            complete: (res) => {
                console.log("openBluetoothAdapter complete:" + res)
            },
            fail: (res) => {
                console.log(JSON.stringify(res))
                wx.showModal({
                    title: "请开启蓝牙",
                    showCancel: false,
                    success:()=>{
                        wx.navigateTo({
                            url: '/pages/index/index',
                        })
                    }
                })
                that.setData({
                    connected: false
                })
                if (res.errCode === 10001) {
                    wx.onBluetoothAdapterStateChange(function (res) {
                        //console.log('onBluetoothAdapterStateChange', res)
                        if (res.available) {
                            //this.createBLEConnection();
                        }
                    })
                }
            }
        })
    },

    createBLEConnection() {

        let that = this;

        const deviceId = this.data.deviceId
        wx.createBLEConnection({
            deviceId,
            success: (res) => {
                that.setData({
                    connected: true,
                })
                this.getBLEDeviceServices(deviceId)
            },
            complete: (res) => {
                console.log("createBLEConnection complete:" + res)
                if (res.errCode === -1) {
                    that.setData({
                        connected: true,
                    })
                    this.getBLEDeviceServices(deviceId)
                }else{
                    wx.showModal({
                        title: "错误设备，连接失败",
                        showCancel: false,
                        success:()=>{
                            wx.navigateTo({
                                url: '/pages/index/index',
                            })
                        }
                    })
                }
            },
        })
    },

    getBLEDeviceServices(deviceId) {
        wx.getBLEDeviceServices({
            deviceId,
            success: (res) => {
                for (let i = 0; i < res.services.length; i++) {
                    if (res.services[i].isPrimary) {
                        this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
                        return
                    }
                }
            }
        })
    },

    getBLEDeviceCharacteristics(deviceId, serviceId) {
        let that = this;
        wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: (res) => {
                console.log('getBLEDeviceCharacteristics success', res.characteristics)
                for (let i = 0; i < res.characteristics.length; i++) {
                    let item = res.characteristics[i]
                    if (item.properties.read) {
                        wx.readBLECharacteristicValue({
                            deviceId,
                            serviceId,
                            characteristicId: item.uuid,
                        })
                    }
                    if (item.properties.write) {
                        that.setData({
                            canWrite: true
                        })
                        that.setData({
                            deviceId: deviceId,
                            serviceId: serviceId,
                            characteristicId: item.uuid
                        })


                        //this.writeBLECharacteristicValue()
                    }
                    if (item.properties.notify || item.properties.indicate) {
                        wx.notifyBLECharacteristicValueChange({
                            deviceId,
                            serviceId,
                            characteristicId: item.uuid,
                            state: true,
                        })
                    }
                }
            },
            fail(res) {
                console.error('getBLEDeviceCharacteristics', res)
            }
        })
        // 操作之前先监听，保证第一时间获取数据
        wx.onBLECharacteristicValueChange((characteristic) => {
            let that = this
            let str = bufferToString(characteristic.value)

            // wx.showModal({
            //   title:str,
            //   showCancel:false
            // })

            if (str === "SSSS") {
                //debugger

                //let sql="update qi_che_she_bei set device_id='"+that.data.deviceId+"' ,  openid='"+wx.getStorageSync('user').openid+"' where device_id='"+that.data.chePaiHao+"'"
                let sql = "update qi_che_she_bei set ming_cheng='" + that.data.chePaiHao + "' ,  openid='" + wx.getStorageSync('user').openid + "' where device_id='" + that.data.deviceId + "'"
                wx.request({
                    url: app.globalData.urlGlobal + '/commonZwl/getZwl', //url
                    method: 'GET', //请求方式
                    header: {
                        'Content-Type': 'application/json',
                    },
                    data: {
                        sql: sql,  //参数
                    },
                    success: function (res) {
                        //debugger
                        let data = res.data.rtn;
                        // if(data.length>=0){
                        wx.showModal({
                            title: "绑定成功",
                            showCancel: false,
                            success(res) {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '/pages/index/index',
                                    })
                                }
                            }
                        })
                        // }

                    },
                    fail: function () {
                        console.log("请求数据失败");
                    },
                    complete: function () {
                        // complete
                    }
                })


            }

            if (str === "EEEE") {
                wx.showModal({
                    title: "wiff链接失败，请重试",
                    showCancel: false
                })
            }

            /*
            wx.showModal({
              title:str,
              showCancel:false
            })
            */

            const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
            const data = {}
            if (idx === -1) {
                data[`chs[${this.data.chs.length}]`] = {
                    uuid: characteristic.characteristicId,
                    value: ab2hex(characteristic.value)
                }

            } else {
                data[`chs[${idx}]`] = {
                    uuid: characteristic.characteristicId,
                    value: ab2hex(characteristic.value)
                }
            }
            // data[`chs[${this.data.chs.length}]`] = {
            //   uuid: characteristic.characteristicId,
            //   value: ab2hex(characteristic.value)
            // }
            this.setData(data)
            console.log(data)
            //this.showModal(JSON.stringify(data))
        })
    },

    writeBLECharacteristicValue(value) {
        if (!this.data.connected) {
            wx.showModal({
                title: '蓝牙连接中',
                showCancel: false
            })
        }
        //value="~!AABW"+value+"\n"
        value = "~!AA" + value + "\n"

        for (let i = 0; i < value.length; i = i + 10) {
            let s = value.substring(i, i + 10)
            this.writeBlue(s)
        }

    },
    writeBlue(val) {
        let that = this;
        let command = val;
        var buf = new ArrayBuffer(command.length); //
        var bufView = new Uint8Array(buf);
        for (var i = 0, strLen = command.length; i < strLen; i++) {
            bufView[i] = command.charCodeAt(i);
        }
        let str = bufferToString(buf)
        console.log(str)
        wx.writeBLECharacteristicValue({
            deviceId: that.data.deviceId,
            serviceId: that.data.serviceId,
            characteristicId: that.data.characteristicId,
            value: buf,
            success: (res) => {
                // wx.showModal({
                //   title:JSON.stringify(res),
                //   showCancel:false
                // })
                console.log(JSON.stringify(str))
            },
            fail: (e) => {
                console.log("writeBlue fail")
                console.log(JSON.stringify(e))
            }
        })


        //this.openBluetoothAdapter();
        //var command=event.currentTarget.dataset.command


        /*
        // 向蓝牙设备发送一个0x00的16进制数据
        let buffer = new ArrayBuffer(1)
        let dataView = new DataView(buffer)
        dataView.setUint8(0, Math.random() * 255 | 0)
        */

        //字符串转为ArrayBuffer对象，参数为字符串
        //var str=this.input_fa_song_value;
        //console.log(str);


    }

})

function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

function bufferToString(buffer) {
    return String.fromCharCode.apply(null, new Uint8Array(buffer))
}